package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class PythonExecutorService {

    private static final Logger logger = LoggerFactory.getLogger(PythonExecutorService.class);

    @Value("${python.script.path:src/main/resources/scripts/}")
    private String scriptPath;

    @Value("${python.executable:python}")
    private String pythonExecutable;

    /**
     * 执行Python脚本
     *
     * @param scriptName 脚本名称
     * @param args       脚本参数
     * @return String 脚本输出
     */
    public String executePythonScript(String scriptName, String... args) {
        try {
            log.info("Executing python script:{} ", scriptName);
            log.info("参数：{} ", Arrays.toString(args));
            // 构建命令
            List<String> command = new ArrayList<>();
            command.add(pythonExecutable);
            command.add(scriptPath + scriptName);
            command.addAll(Arrays.asList(args));

            // 创建ProcessBuilder
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            // 启动进程
            Process process = processBuilder.start();
            // 读取输出
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }
            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                logger.error("Python script execution failed with exit code: {}", exitCode);
                throw new RuntimeException("Python script execution failed");
            }
            return output.toString().trim();
        } catch (Exception e) {
            logger.error("Error executing Python script: ", e);
            throw new RuntimeException("Failed to execute Python script", e);
        }
    }

    /**
     * 异步执行Python脚本
     */
    @Async
    public CompletableFuture<String> executePythonScriptAsync(String scriptName, String... args) {
        return CompletableFuture.completedFuture(executePythonScript(scriptName, args));
    }
}
